
from flask import Flask, request, jsonify
from flask_cors import CORS

from models import *

app = Flask(__name__)

#配置当前应用允许跨域访问
CORS(app, resources={r"/*": {"origins": "*"}})

#配置数据库 URI
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///chat.db'
db.init_app(app)

#建表
with app.app_context():
    db.create_all()

#register
@app.route('/register', methods=['POST'])
def register():
   try:

       # 1.接收数据
       username = request.get_json().get('username')
       password = request.get_json().get('password')

       # 2.判断账号是否重复 （查询）
       user = User.query.filter_by(username=username).first()
       if user:
            return jsonify({'success': False, 'message': '账号已存在'})
       else:

        # 3.注册（添加）
        #3.1.加密
            password = User.set_password(password)
            user = User(username=username, password_hash=password)
        # 3.2.执行添加操作
            db.session.add(user)
            db.session.commit()
            return jsonify({'success': True, 'message': '注册成功'})



   except Exception as e:
       print(f'{e}')
       return jsonify({'success': False, 'message': '注册失败，出错了！'})

@app.route('/login', methods=['POST'])
def login():
    try:
        username = request.get_json().get('username')
        password = request.get_json().get('password')

        user = User.query.filter_by(username=username).first()
        if user and user.check_password(password):
            return jsonify({'success': True, 'message': '登录成功','user':user.to_dict()})
        else:
            return jsonify({'success': False, 'message': '无效账号'})
    except Exception as e:
        print(f'{e}')
        return jsonify({'success': False,'message':'登录失败账号密码有误'})


#查询当前好友
@app.route('/get_friends', methods=['GET'])
def get_friends():
    try:
        # 获取查询参数
        user_id = request.args.get('userId')
        friends_list = Friend.query.filter_by(user_id=user_id).all()
        return jsonify({'success': True, 'friends': [f.to_dict() for f in friends_list]})
    except Exception as e:
        print(f'{e}')
        return jsonify({'success': False, 'message': '查询失败！'})

@app.route('/')
def hello_world():  # put application's code here
    return 'Hello World!'





if __name__ == '__main__':
    app.run()
